package in.muton.edushare.pages.publicpages.univpages;

import in.muton.edushare.processing.objects.UnivDataHandler;
import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.InnerList;
import in.muton.panels.paginator.EntityListing;

import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.Courses;

public class UnivPublicCourse extends UnivBasePublic {

	public UnivPublicCourse(PageParameters params) {
		super(params);
		add(new Link<Void>("allCourses") {
			@Override
			public void onClick() {
				setSearchTerm("");
			}

			private static final long serialVersionUID = 5255465247133387224L;
		});

		Form<Void> f = new Form<Void>("searchForm");
		f.add(new TextField<String>("searchTerm", new PropertyModel<String>(
				this, "searchTerm")));
		add(f);
		f.add(new SubmitLink("submitLink"));

		add(new EntityListing<Courses>("thumbList", new InnerList<Courses>() {
			private static final long serialVersionUID = -56856143743214954L;

			@Override
			public List<IModel<Courses>> getObject() {
				CayenneList<Courses> totalCourseList = new UnivDataHandler(
						getUnivModel()).getCourses();
				totalCourseList = filterCourses(totalCourseList);
				return totalCourseList.getObject();
			}
		}, this));
	}

	public CayenneList<Courses> filterCourses(CayenneList<Courses> courseList) {
		if (!StringUtil.isValid(searchTerm))
			return courseList;
		CayenneList<Courses> newList = new CayenneList<Courses>(null);
		List<IModel<Courses>> tempList = courseList.getObject();
		for (IModel<Courses> t : tempList) {
			if (t.getObject().getCourseName().toLowerCase().trim().contains(
					searchTerm.toLowerCase().trim())) {
				newList.add(t.getObject());
			}
		}
		return newList;
	}

	@Override
	public String getPageName(PageParameters params) {
		return "univPublicCourse";
	}

	public void setSearchTerm(String searchTerm) {
		this.searchTerm = searchTerm;
	}

	public String getSearchTerm() {
		return searchTerm;
	}

	private String searchTerm = "";
}
